﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Imageo.bintje;
using System.Web.UI;
using System.Drawing;

namespace Imageo
{
    /// <summary>
    /// Bitmap resampling helper class
    /// </summary>
    public class BitmapHelper
    {
        /// <summary>
        /// Resizes the bitmap image
        /// </summary>
        /// <param name="b">input bitmap</param>
        /// <param name="nWidth">output bitmap width</param>
        /// <param name="nHeight">output bitmap height</param>
        /// <returns>resized bitmap</returns>
        public static Bitmap ResizeBitmap(Bitmap sourceBitmap, int maxWidth, int maxHeight)
        {
            return ResizeBitmap(sourceBitmap, maxWidth, maxHeight, true);
        }
        
        /// <summary>
        /// Resizes the bitmap image
        /// </summary>
        /// <param name="sourceBitmap"></param>
        /// <param name="maxWidth"></param>
        /// <param name="maxHeight"></param>
        /// <returns></returns>
        public static Bitmap ResizeBitmap(Bitmap sourceBitmap, int maxWidth, int maxHeight, bool keepAspectRatio)
        {
            double newWidth = maxWidth;
            double newHeight = maxHeight;

            if (keepAspectRatio)
            {
                // Find the longest and shortest dimentions  
                int longestDimension = (sourceBitmap.Width > sourceBitmap.Height) ? sourceBitmap.Width : sourceBitmap.Height;
                int shortestDimension = (sourceBitmap.Width < sourceBitmap.Height) ? sourceBitmap.Width : sourceBitmap.Height;

                double factor = ((double)longestDimension) / (double)shortestDimension;

                newHeight = maxWidth / factor;

                //If height is actually greater, then we reset it to use height instead of width  
                if (sourceBitmap.Width < sourceBitmap.Height)
                {
                    newWidth = maxHeight / factor;
                    newHeight = maxHeight;
                }
            }

            // Create new Bitmap at new dimensions based on original bitmap  
            Bitmap resizedBitmap = new Bitmap((int)newWidth, (int)newHeight);
            using (Graphics g = Graphics.FromImage((System.Drawing.Image)resizedBitmap))
                g.DrawImage(sourceBitmap, 0, 0, (int)newWidth, (int)newHeight);
            return resizedBitmap;
        } 
    }
}